//
//  CNStatusPicturesView.swift
//  Ccweibo
//
//  Created by 陈锦聪 on 16/3/26.
//  Copyright © 2016年 Coco. All rights reserved.
//

import UIKit
import SDWebImage

class CNStatusPicturesView: UICollectionView {

    let layout = UICollectionViewFlowLayout()
    
    var pictureURLs: [NSURL]? {
        didSet {
            let size = calculateViewSize()
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(size)
            }
            // 刷新 (覆盖复用的cell)
            reloadData()
        }
    }
    private func calculateViewSize() -> CGSize {
        // 默认
        layout.itemSize = CGSize(width: cellWH, height: cellWH)
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        let count = pictureURLs?.count ?? 0
        // 无图
        if count == 0 {
            layout.itemSize = CGSizeZero
            return CGSizeZero
        }
        // 单图
        if count == 1 {
            var imageSize = CGSize(width: cellWH, height: cellWH)
            let urlString = pictureURLs![0].absoluteString
            if let image = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(urlString) {
                imageSize = image.size
            }
            if imageSize.width < 50 {
                imageSize.width = 50
            }
            if imageSize.width > UIScreen.width / 2 {
                imageSize.width = UIScreen.width / 2
            }
            layout.itemSize = imageSize
            return imageSize
        }
        // 以下为多图的情况
        var cols = maxCols
        layout.minimumLineSpacing = defaultGap 
        layout.minimumInteritemSpacing = defaultGap
        if count == 2 || count == 4 {
            cols = 2
        }
        let rows = (count + cols - 1) / cols
        let width = cellWH * CGFloat(cols) + defaultGap * CGFloat(cols - 1)
        let height = cellWH * CGFloat(rows) + defaultGap * CGFloat(rows - 1)
        return CGSize(width: width, height: height)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    init() {
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        self.dataSource = self
        registerClass(CNPicturesViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        // 点击状态栏能否滚动到最顶点
        self.scrollsToTop = false
        self.backgroundColor = UIColor.clearColor()
    }
    
    
}

private let reuseIdentifier = "CNPicturesViewCell"

extension CNStatusPicturesView: UICollectionViewDataSource {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictureURLs?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CNPicturesViewCell
        cell.imageURL = pictureURLs?[indexPath.item]
        return cell
    }
}

class CNPicturesViewCell: UICollectionViewCell {
    
    var imageURL: NSURL? {
        didSet {
            if let url = imageURL {
                bgImageView.sd_setImageWithURL(url)
            }
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        prepareUI()
    }

    private func prepareUI() {
        
        contentView.addSubview(bgImageView)
        
        // 图片填充模式
        bgImageView.contentMode = UIViewContentMode.ScaleAspectFill
        // 剪切超出部分
        bgImageView.clipsToBounds = true
        
        bgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
    }
    private lazy var bgImageView: UIImageView = UIImageView()
}

